<?php

namespace app\admin\controller;
use think\Db;
use app\common\controller\Backend;
use app\admin\model\Plan;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\Session;

/**
 * zc_record 日志表 --老汉
 *
 * @icon fa fa-circle-o
 */
class Record extends Backend
{

    /**
     * Record模型对象
     * @var \app\admin\model\Record
     */
    protected $model = null;
    protected $noNeedRight = ['detail','exportRecord','dashMyRecord'];
    protected $dataLimit = 'personal'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段
    protected $admin_id = 0;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Record;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->admin_id = Session::get("admin")['id'];
    }

    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;

                //添加参数
                $params = $this->handParam($params);

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($params['plan']==1){
                        $this->success('成功','plan/index');
                    }else{
                        $this->success();
                    }

                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function detail($ids){
        $list = $this->model->get($ids);
        $this->assign('list',$list);
        return $this->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;

                //添加参数
                $params = $this->handParam($params);

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    //处理参数
    public function handParam($params){
        //实例化
        $plan = new Plan();
        //根据计划id获取计划信息
        $planInfo = $plan->getInfo($params['plan_id'])[0];
        //把项目id加入参数
        $params['project_id'] = $planInfo['project_id']?$planInfo['project_id']:'';
        return $params;
    }


    //导出日志
    public function exportRecord() {
        Loader::import('PHPExcel.PHPExcel', EXTEND_PATH, '.php');
        //获取要导出的数据
        $admin_id = $this->admin_id;
        $list = Db::query("
                SELECT
                    `remarks`,`title`
                FROM
                    `zc_record`
                WHERE
                    `admin_id` = {$admin_id} AND
                `deletetime` IS NULL
                ORDER BY
                    `id` ASC
            ");
        foreach ($list as $k => $v) {
            $list[$k]['remarks'] = strip_tags($v['remarks']);
        }
        //2.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //3.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //4.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '标题')
            ->setCellValue('B1', '内容');
        //设置单元格宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(50);
        //5.循环刚取出来的数组，将数据逐一添加到excel表格。
        for($i=0;$i<count($list);$i++){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.($i+2),$list[$i]['title']);//添加ID
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($i+2),$list[$i]['remarks']);//添加ID
        }
        //6.设置保存的Excel表格名称
        $filename = '日志信息'.date('YmdHis',time()).'.xls';
        //7.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('日志信息');
        //8.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }

    public function dashMyRecord() {
        $info = $this->model->getInfo(null,null,null,$this->admin_id,null,"weigh desc,id desc",10);
        return json(["code"=>1,"msg"=>"获取成功","data"=>$info]);
    }


}
